/*####################################################################################
  CLASS : mydojo.dijix.SimpleChart
  ==================================
  - A simple chart widget (same hr.level as SimpleGrid/ContentPane - Data format same)
  
  - It is a SubView, can be inserted into ViewPanel directly
  
  - Implements: subView.render() and subView.clean();
  
  By: P.M.Shrestha  
  ####################################################################################*/
  
dojo.provide("mydojo.dijix.SimpleChart");
dojo.provide("mydojo.core.String");

dojo.require("dojox.charting.Chart2D");
dojo.require("dijit.layout.ContentPane");
dojo.require("dojox.charting.themes.PlotKit.blue");

dojo.declare("mydojo.dijix.SimpleChart", dijit.layout.ContentPane , {
		// Data format -> [ [ "x-label" , y-val-1 , y-val-2 ] , [...] , ... ]
		data 		: [ [ "12:00:00",3,2,1,12] , ["13:00:00",4,2,3,10] , [ "14:00:00",2,5,4,9] , ["15:00:00",1,2,3,6] , [ "12:00:00",3,2,1,12] , ["13:00:00",4,2,3,10] , [ "14:00:00",2,5,4,9] , ["15:00:00",1,2,3,6] ],		
		// Chart legend....
		chartStruct : [	{name: 'Max' , color:'red'  ,show:true  }, 
						{name: 'Min' , color:'green' ,show:true    },
						{name: 'Avg' , color:'blue'  ,show:true },
						{name: 'Sum' , color:'#34F234' ,show:true  }												
					  ],
		seriesCount: 0,
		seriesIndex: [],		  
		xLabel: "x-axis" ,
		yLabel: "y-axis" ,
		chartWt		: null,
		// ======================================================================
		//	Post create widget - Create grid widget inside the CP
		// ----------------------------------------------------------------------
		postCreate: function() {		
			this.inherited(arguments);				
		
			// create chart dom
			var node = document.createElement("div");
			node.style.cssText = "width:100%;height:90%;"
			node.id = this.id+"_chart";
			this.domNode.appendChild(node);
		
			// create legend dom
			node = node = document.createElement("div");
			node.style.cssText = "width:100%;height:10%;"
			node.id = this.id+"_legend";
			this.domNode.appendChild(node);
		
		},
		// ======================================================================
		//	Draw Chart 
		// ----------------------------------------------------------------------	
		drawChart: function(data){			
			if(data != null)
				this.data = data;
			// Remove previous chart if any								
			dojo.byId(this.id+"_chart").innerHTML = "";	

			// Resize the chart div to occupy the ContentPane
			dojo.byId(this.id+"_chart").style.width 	= dojo.marginBox(this.domNode).w + "px";
			dojo.byId(this.id+"_chart").style.height	= dojo.marginBox(this.domNode).h*(90/100) + "px";			
			
			// Prepare series lables and data
			var seriesLabel = new Array( this.data.length );
			var seriesData  = new Array(); 
			this.seriesCount = 0;
			this.seriesIndex = [];
			
			for( var h=0 ; h < this.chartStruct.length ; h++){
				if(this.chartStruct[h].show){
					seriesData[this.seriesCount] = new Array(this.data.length);
					this.seriesIndex[this.seriesCount] = h;
					this.seriesCount++;					
				}	
			}

			// Populate series label and data
			for( var i=0 ; i < this.data.length ; i++){
				seriesLabel[i] = {value: i+1 , text: this.data[i][0]};
				for( var j=0 ; j < this.seriesCount ; j++)
					seriesData[j][i] = this.data[i][this.seriesIndex[j]+1];
			}						
			// Create a new chart	
			this.chartWt = new dojox.charting.Chart2D( this.id+"_chart"  );									
			this.chartWt.setTheme(dojox.charting.themes.PlotKit.blue);
			
			// Draw chart
			this.chartWt.addPlot("default", {type: "Lines" , markers:true });									
			this.chartWt.addAxis("x" , { labels: seriesLabel , majorTickStep: 1 , minorTickStep: 1 });										
			this.chartWt.addAxis("y" , { vertical: true 	 , majorTickStep: 5 , minorTickStep: 2} );
				
			// Draw the series plots						
			for( var i=0 ; i<seriesData.length ; i++ )
				this.chartWt.addSeries( mydojo.core.underscore(this.chartStruct[this.seriesIndex[i]].name) , seriesData[i] , { stroke: {color:this.chartStruct[this.seriesIndex[i]].color} });							

			// add grid
			this.chartWt.addPlot("Grid", {type: "Grid",
				hAxis: "x", vAxis: "y",
				hMajorLines: true,	hMinorLines: false,	
				vMajorLines: true,	vMinorLines: false
			});	
			this.chartWt.render();
    		this.drawAxisLabel();
    		this.drawLegend();
		},
		drawAxisLabel: function(){
			this.makeAxisTitle(this.chartWt,this.chartWt.axes["x"],this.xLabel);		
    		this.makeAxisTitle(this.chartWt,this.chartWt.axes["y"],this.yLabel);		
		},
		drawLegend: function(){
			var leg = dojo.byId(this.id+"_legend");
			leg.innerHTML = "";
			dojo.forEach(this.chartStruct, function(ele){ 
				if(ele.show)
					leg.innerHTML += "&nbsp;&nbsp;&nbsp;<span style=\"width:12px;height:12px;background:"+ele.color+"\">&nbsp;&nbsp;&nbsp;&nbsp;</span>&nbsp;<span>"+ele.name+"</span>" 
			});			
		},
		// ======================================================================
		//	Draw Axis Title on Chart
		// ----------------------------------------------------------------------	
		makeAxisTitle: function(chart,axis,label){
		    var dim = chart.dim;
		    var offsets=chart.offsets;
		    var ta = chart.theme.axis;
		    var taFont = "font" in axis.opt ? axis.opt.font : ta.font;
		    var x;var y;
		    var rotate=0;		    
		    if(axis.vertical){
		        rotate=270 ; y=dim.height/2  - offsets.b/2 + 12 ; x = 0+17;		        
		    }else{
		        x=(dim.width/2 + offsets.l/2) ; y=dim.height-5;}
		    var m = dojox.gfx.matrix;
		    var elem = axis.group.createText({x:x, y:y, text:label, align: "middle"});
		    elem.setFont({family:"Tahoma", size: "7pt", weight: "bold" });
		    elem.setFill( axis.vertical? '#0000FF' : '#FF0000');
		    elem.setTransform(m.rotategAt(rotate, x,y));
		},
		// ======================================================================
		//	Render response from server 
		// ----------------------------------------------------------------------	
		render: function(response,event){
			this.drawChart(response);
		},
		// ======================================================================
		//	Clean up this widget
		// ----------------------------------------------------------------------	
		clean: function(){		
			console.log("Running SimpleChart.clean() function.id:" + this.id);                      	        	        	          	

		},
		// ======================================================================
		//	Resize SimpleChart
		// ----------------------------------------------------------------------	
		resize: function(){
			this.inherited(arguments);							
			if(this.chartWt != null){
				this.chartWt.resize(dojo.marginBox(this.domNode).w ,dojo.marginBox(this.domNode).h*90/100);
				this.drawAxisLabel();
			}
		}
});


